package com.jjsc.product.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjsc.common.core.exception.ServiceException;
import com.jjsc.common.core.utils.StringUtils;
import com.jjsc.common.security.utils.SecurityUtils;
import com.jjsc.product.api.domain.Category;
import com.jjsc.product.api.domain.dto.CategoryTreeVO;
import com.jjsc.product.mapper.CategoryMapper;
import com.jjsc.product.service.ICategoryService;
import com.jjsc.product.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: 钟城明
 * @CreateTime: 2025-10-11
 * @Description:
 * @Version: 1.0
 */

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {


    @Override
    public List<CategoryTreeVO> getCategoryTree(Category category) {
        List<Category> list = this.list(new LambdaQueryWrapper<Category>()
                .like(StringUtils.hasText(category.getName()), Category::getName, category.getName())
                .eq(Category::getDelFlag, "0")
                .orderByAsc(Category::getSort));
        return buildTree(list, 0L);
    }

    private List<CategoryTreeVO> buildTree(List<Category> all, long parentId) {
        return all.stream()
                .filter(item -> Objects.equals(item.getParentId(), parentId))
                .map(item -> {
                    CategoryTreeVO vo = new CategoryTreeVO();
                    vo.setCategoryId(item.getCategoryId());
                    vo.setName(item.getName());
                    vo.setParentId(item.getParentId());
                    vo.setLevel(item.getLevel());
                    vo.setSort(item.getSort());
                    vo.setStatus(item.getStatus());
                    vo.setChildren(buildTree(all, item.getCategoryId()));
                    vo.setImage(item.getImage());
                    vo.setCreateTime(item.getCreateTime());
                    return vo;
                })
                .sorted(Comparator.comparing(CategoryTreeVO::getSort))
                .collect(Collectors.toList());
    }

    @Override
    public void addCategory(Category category) {
        //设置创建人（若依自动填充）
        category.setCreateBy(SecurityUtils.getUsername());
        category.setCategoryId(null);
        if (category.getParentId() == 0) {
            category.setLevel(1);
        } else {
            Category parent = this.getById(category.getParentId());
            if (parent == null || "2".equals(parent.getDelFlag())) {
                throw new ServiceException("父分类不存在");
            }
            if (parent.getLevel() >= 3) {
                throw new ServiceException("分类最多支持3级");
            }
            category.setLevel(parent.getLevel() + 1);
        }

        // 同级分类名称唯一校验
        boolean exists = this.lambdaQuery()
                .eq(Category::getParentId, category.getParentId())
                .eq(Category::getName, category.getName())
                .eq(Category::getDelFlag, "0")
                .exists();
        if (exists) {
            throw new ServiceException("同级分类名称不能重复");
        }

        this.save(category);
    }

    @Override
    public void updateCategory(Category category) {
        Category old = this.getById(category.getCategoryId());
        if (old == null || "2".equals(old.getDelFlag())) {
            throw new ServiceException("分类不存在");
        }

        // 名称唯一校验（排除自己）
        boolean exists = this.lambdaQuery()
                .ne(Category::getCategoryId, category.getCategoryId())
                .eq(Category::getParentId, old.getParentId())
                .eq(Category::getName, category.getName())
                .eq(Category::getDelFlag, "0")
                .exists();
        if (exists) {
            throw new ServiceException("同级分类名称不能重复");
        }

        category.setParentId(old.getParentId());
        category.setLevel(old.getLevel());
        category.setUpdateBy(SecurityUtils.getUsername());
        this.updateById(category);
    }

    @Override
    public void deleteCategory(Long categoryId) {
        // 检查是否有关联商品
        // if (productService.existsByCategoryId(categoryId)) {
        //     throw new ServiceException("该分类下存在商品，无法删除");
        // }

        List<Long> ids = new ArrayList<>();
        collectChildren(categoryId, ids);
        this.lambdaUpdate()
                .set(Category::getDelFlag, "2")
                .set(Category::getUpdateBy, SecurityUtils.getUsername())
                .in(Category::getCategoryId, ids)
                .update();
    }

    @Override
    public List<CategoryVo> getLevelOneCategory() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getParentId, 0)
                .eq(Category::getDelFlag, "0")
                .orderByAsc(Category::getSort);
        List<Category> categoryList = this.list(wrapper);
        if (CollectionUtils.isNotEmpty(categoryList)) {
            List<CategoryVo> categoryVoList = categoryList.stream()
                    .map(category -> {
                        CategoryVo categoryVo = new CategoryVo();
                        BeanUtils.copyProperties(category, categoryVo);
                        return categoryVo;
                    }).collect(Collectors.toList());
            return categoryVoList;
        }
        return null;
    }

    //================================================================================================================
    private void collectChildren(Long parentId, List<Long> result) {
        result.add(parentId);
        List<Category> children = this.lambdaQuery()
                .eq(Category::getParentId, parentId)
                .eq(Category::getDelFlag, "0")
                .list();
        if (CollectionUtils.isNotEmpty(children)) {
            for (Category child : children) {
                collectChildren(child.getCategoryId(), result);
            }
        }
    }


    /**
     * 分类树
     *
     * @return
     */
    @Override
    public List<CategoryVo> tree() {
        //查询首页分类
        List<Category> categoryList = baseMapper.selectList(null);
        if (!CollectionUtils.isEmpty(categoryList)) {
            List<CategoryVo> categoryVoList = categoryList.stream()
                    .map(category -> {
                        CategoryVo categoryVo = new CategoryVo();
                        BeanUtils.copyProperties(category, categoryVo);
                        return categoryVo;
                    }).collect(Collectors.toList());
            return buildCreategoryTree(categoryVoList);
        }

        return  null;
    }

    private List<CategoryVo> buildCreategoryTree(List<CategoryVo> categoryVoList) {
        List<CategoryVo> topCategoryList = new ArrayList<>();


        Map<Long, CategoryVo> categoryVoMap = categoryVoList
                .stream()
                .collect(Collectors.toMap(CategoryVo::getCategoryId, t -> t));

        for (CategoryVo categoryVo : categoryVoList) {
            if (categoryVo.getParentId() == 0) {
                topCategoryList.add(categoryVo);
            } else {
                Long parentId = categoryVo.getParentId();
                categoryVoMap.get(parentId).getChildren().add(categoryVo);
            }
        }

        return topCategoryList;
    }
}
